package cn.uncode.rpc.common.message;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;


/**
 * @author wj.ye
 */
public class Messages {
	
    private static final String BUNDLE_NAME = "messages/messages";

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
    
    private static final int MISSING_RESOURCE_EXCEPTION_CODE = 40001;
    private static final String MISSING_RESOURCE_EXCEPTION_MSG = "Key [{0}] missing message resource.";

    private Messages() {}

    public static Message getString(String key) {
    	Message message = null;
        try {
        	String msg = RESOURCE_BUNDLE.getString(key);
        	message = Message.valueOf(msg);
        } catch (MissingResourceException e) {
        	message = buildMissingResourceMessage(key);
        }
        return message;
    }

    public static Message getString(String key, String parm1) {
    	Message message = null;
        try {
        	String msg = RESOURCE_BUNDLE.getString(key);
        	msg =  MessageFormat.format(msg, parm1);
        	message = Message.valueOf(msg);
        } catch (MissingResourceException e) {
        	message = buildMissingResourceMessage(key);
        }
        return message;
    }

    public static Message getString(String key, String parm1, String parm2) {
    	Message message = null;
        try {
        	String msg = RESOURCE_BUNDLE.getString(key);
        	msg =  MessageFormat.format(msg, new Object[] { parm1, parm2 });
        	message = Message.valueOf(msg);
        } catch (MissingResourceException e) {
        	message = buildMissingResourceMessage(key);
        }
        return message;
    }

    public static Message getString(String key, String parm1, String parm2,
            String parm3) {
    	Message message = null;
        try {
        	String msg = RESOURCE_BUNDLE.getString(key);
        	msg =  MessageFormat.format(msg, new Object[] {parm1, parm2, parm3});
        	message = Message.valueOf(msg);
        } catch (MissingResourceException e) {
        	message = buildMissingResourceMessage(key);
        }
        return message;
    }
    
    public static Message getString(String key, String parm1, String parm2,
            String parm3, String parm4) {
    	Message message = null;
        try {
        	String msg = RESOURCE_BUNDLE.getString(key);
        	msg =  MessageFormat.format(msg, new Object[] {parm1, parm2, parm3, parm4});
        	message = Message.valueOf(msg);
        } catch (MissingResourceException e) {
        	message = buildMissingResourceMessage(key);
        }
        return message;
    }
    
    private static Message buildMissingResourceMessage(String key){
    	return new Message(MISSING_RESOURCE_EXCEPTION_CODE, MessageFormat.format(MISSING_RESOURCE_EXCEPTION_MSG, key));
    }
}
